<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-7-27
 * Time: 下午2:53
 */
namespace Tiny;

abstract class JsonAPI extends API{
  protected function beforeRun(Request $request, Response $response):bool {
    //empty：判断是否存在，非零，字符串非空
    if (empty($request->data)){
      $request->data = new \stdClass();
    }else{
      $request->data = json_decode($request->data);
    }
    if ($request->data == false){
      $response->httpStatus = HttpStatus::ARGS_FORMAT_ERROR;
      $response->httpStatusMsg = "api json_decode($request->data) is error";
      return false;
    }
    return true;
  }

  protected function afterRun(Request $request, Response $response) {
    if (!isset($request->data) || $request->data == null){
      $response->httpStatus = HttpStatus::ARGS_ERROR;
      $response->httpStatusMsg = "response data is not set";
      return;
    }
    $response->data = json_encode($response->data);
    if ($response->data == false){
      $response->httpStatus = HttpStatus::ARGS_FORMAT_ERROR;
      $response->httpStatusMsg = "api json_encode($response->data) error";
    }
  }
}